package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.ClearBusAccSystemUtils;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.DailyReportRelated;
import com.customization.unionpay.market.util.PropUtils;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author sjm
 * @description 资金划拨单营销相关
 */
public class MarketOfFundTransferAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketOfFundTransferAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {

        OverTimeSetBean overTimeBean = new OverTimeSetBean();

        RequestManager rm = requestInfo.getRequestManager();

        try {
            String src = rm.getSrc();
            log.info("src："+src);
            int nodeId = rm.getNodeid();
            int formId = rm.getFormid();                       // 流程表单id

            // 划拨类型
            String hblxYx = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "hblx", "营销资金补足");
            log.info("营销资金补足：" + hblxYx);
            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);
            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            String hblx = mainMap.get("hblx");
            log.info("hblx：" + hblx);
            if(hblx.equals(hblxYx)){
                log.info("营销发起资金划拨单!");
                // 营销活动日报表台账表单id
                int reportFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));

                String qksptgValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zt", "请款审批通过");
                log.info("请款审批通过枚举值：" + qksptgValue);
                String qkspwtgValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zt", "请款审批未通过");
                log.info("请款审批未通过枚举值：" + qkspwtgValue);
                String fkzValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zt", "付款中");
                log.info("付款中枚举值：" + fkzValue);
                String fzsbValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zt", "付款失败");
                log.info("付款失败枚举值：" + fzsbValue);
                String yfkValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zt", "已付款");
                log.info("已付款枚举值：" + yfkValue);

                String nbyxValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zjly", "内部营销");
                log.info("内部营销枚举值：" + nbyxValue);
                String nwbyxValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zjly", "内外部联合营销");
                log.info("内外部联合营销枚举值：" + nwbyxValue);


                String yzfValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "fkzt", "已支付");
                log.info("已支付枚举值：" + yfkValue);
                String dailyReportTableName = FormDataUtils.getTableName(reportFormId);
                log.info("dailyReportTableName："+dailyReportTableName);

                // 所有明细表的值
                Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");
                Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                if ("reject".equals(src)) {
                    updateDailyState(dt1,dailyReportTableName,2, qksptgValue, qkspwtgValue, fkzValue, fzsbValue, yfkValue, yzfValue,nbyxValue,nwbyxValue);
                } else {
                    String nodeName = overTimeBean.getNodeName(nodeId);
                    if ("资金支付".equals(nodeName)) {
                        updateDailyState(dt1,dailyReportTableName,1, qksptgValue, qkspwtgValue, fkzValue, fzsbValue, yfkValue, yzfValue,nbyxValue,nwbyxValue);
                    }
                }
            }else {
                log.info("非营销发起资金划拨单!");
            }
        } catch (Exception e) {
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 修改日报表台账状态
     * @param dt1
     * @param tableName
     * @param sign                     1、请款审批通过  2、请款审批未通过 3、其他
     * @param qksptgValue
     * @param qkspwtgValue
     * @param fkzValue
     * @param fzsbValue
     * @param yfkValue
     */
    public void updateDailyState(Map<String, Map<String, String>> dt1,String tableName,Integer sign,String qksptgValue,String qkspwtgValue,String fkzValue,String fzsbValue,String yfkValue,String yzfValue,String nbyxValue,String nwbyxValue) throws Exception {
        for (String key : dt1.keySet()) {
            Map<String, String> value = dt1.get(key);
            // 请款批次号
            String qkpch = value.get("qkpch");
            // 支付状态
            String yszrzx = value.get("fkzt");
            if(sign == 1){
                log.info("请款审批通过,qksptgValue："+qksptgValue+",qkpch:"+qkpch+",tableName:"+tableName);
//                DailyReportRelated.updateZtByPch(qksptgValue,qkpch,tableName);
                DailyReportRelated.updateZtByPch(fkzValue,qkpch,tableName);
            }else if(sign == 2){
                log.info("请款审批未通过,qkspwtgValue："+qkspwtgValue+",qkpch:"+qkpch+",tableName:"+tableName);
                DailyReportRelated.updateZtByPch(qkspwtgValue,qkpch,tableName);
            }else {
                log.info("其他通过,yzfValue："+yzfValue+",yszrzx:"+yszrzx+",qkspwtgValue:"+qkspwtgValue+",qkpch:"+qkpch+",yfkValue:"+yfkValue+",nbyxValue:"+nbyxValue+",nwbyxValue:"+nwbyxValue+",fkzValue:"+fkzValue);
                if(yzfValue.equals(yszrzx)){
                    DailyReportRelated.updateZtByPch(yfkValue,qkpch,tableName);
                    // 推送已支付的状态
                    initiateBusinessAccountBookkeeping(qkpch,tableName,nbyxValue,nwbyxValue);
                }else {
                    DailyReportRelated.updateZtByPch(fzsbValue,qkpch,tableName);
                }
            }
        }
    }

    /**
     * 调用清算业务核算系统业务账号记账
     * @param qkpch
     * @param reportFormTableName
     * @param nbyxValue
     * @param nwbyxValue
     */
    private void initiateBusinessAccountBookkeeping(String qkpch,String reportFormTableName,String nbyxValue,String nwbyxValue) throws Exception {
        String requestSysCode = PropUtils.BB_LOG.getPropValue("marketSubject", "requestSysCode");
        // 借贷平衡
        List<JSONObject> list = DailyReportRelated.selectDataByPch(qkpch, reportFormTableName);
        if(list.size() > 0){
            for (JSONObject data : list) {
                String zjly = data.getString("zjly");
                String yxpthdsqm = data.getString("yxpthdsqm");
                Double rzje = data.getDouble("rzje");

                List<JSONObject> params = new ArrayList<>();
                String bussSn = UUID.randomUUID().toString();
                JSONObject borrowData = new JSONObject();
                JSONObject loan = new JSONObject();
                // 内部授权码
                if(zjly.equals(nbyxValue)){
                    if(rzje >= 0){
                        // 正数 借: 00000001 贷: 授权码+02
                        borrowData = combiningFixedParameters(bussSn, "1", "00000001", rzje.toString());
                        loan = combiningFixedParameters(bussSn,"2",yxpthdsqm+"02",rzje.toString());
                    }else {
                        // 负数 借: 授权码+02 贷: 00000001
                        borrowData = combiningFixedParameters(bussSn,"1",yxpthdsqm+"02",rzje.toString());
                        loan = combiningFixedParameters(bussSn,"2","00000001",rzje.toString());
                    }
                }
                // 内外部授权码
                if(zjly.equals(nwbyxValue)){
                    if(rzje >= 0){
                        // 正数 借: 00000001 贷: 授权码+01
                        borrowData = combiningFixedParameters(bussSn,"1","00000001",rzje.toString());
                        loan = combiningFixedParameters(bussSn,"2",yxpthdsqm+"01",rzje.toString());
                    }else {
                        // 负数 借: 授权码+01 贷: 00000001
                        borrowData = combiningFixedParameters(bussSn,"1",yxpthdsqm+"01",rzje.toString());
                        loan = combiningFixedParameters(bussSn,"2","00000001",rzje.toString());
                    }
                }

                params.add(borrowData);
                params.add(loan);
                // 发起记账
                String businessAccountBookkeeping = ClearBusAccSystemUtils.businessAccountBookkeeping(params, requestSysCode);
                log.info("businessAccountBookkeeping："+businessAccountBookkeeping);

            }
        }else {
            log.info("根据请款批次号查询日报表为空！");
        }
    }

    /**
     * 组合固定参数
     * @return
     */
    /**
     *
     * @param bussSn              业务流水号
     * @param occurDirect         记账方向     "1":借  "2":贷
     * @param acctNo              业务账号
     * @param bussAt              业务金额
     * @return
     */
    private JSONObject combiningFixedParameters(String bussSn,String occurDirect,String acctNo,String bussAt){
        JSONObject res = new JSONObject();
        // 币种        bussCurr           "CNY"
        res.put("bussCurr","CNY");
        // 汇率	    chgRate             1.00
        res.put("chgRate","1.00");
        // 记账类型	finType            "03":发生
        res.put("finType","03");
        // 记账类别	occurTp            "01": 普通记账
        res.put("occurTp","01");
        // 附言	    remark
        res.put("remark","");
        // 记账方向	occurDirect        "1":借  "2":贷
        res.put("occurDirect",occurDirect);
        // 业务流水号	bussSn
        res.put("bussSn",bussSn);
        // 业务账号	acctNo
        res.put("acctNo",acctNo);
        // 业务金额     bussAt
        res.put("bussAt", bussAt);
        return res;
    }

}
